import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router/index'
// 创建axios实例
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 10000
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  // 从pinia中获取token
  const userStore = useUserStore()
  // 判断token是否存在
  if (userStore.userInfo.token) {
    // 存在则添加token到请求头中
    config.headers.Authorization = `Bearer ${userStore.userInfo.token}`
  }
  // 返回配置
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  const userStore = useUserStore()
  // 请求失败时显示提示信息
  ElMessage.warning(e.response.data.message)
  // 401状态码表示token失效，需要重新登录
  if (e.response.status === 401) {
    // 重新登录
    userStore.clearUserInfo()
    // 跳转到登录页面
    router.push('/login')
  }
  return Promise.reject(e)
})


export default httpInstance